

#import "QuartzCore/QuartzCore.h"
#import "EMAsyncFile.h"

@interface EMAsyncFile()

	@property (nonatomic, strong) NSURLConnection			*connection;
	@property (nonatomic, strong) NSMutableData				*data;
	@property (nonatomic, strong) NSString					*filePath;
	@property (nonatomic, assign) BOOL	isInResuableCell;
    @property (nonatomic, strong) NSString	*imageType;

@end

@implementation EMAsyncFile {

}

@synthesize imageId, imageUrl, imageIdKey;
@synthesize connection, data, filePath, imageType, isInResuableCell;



- (void)setImageId:(NSString *)anId {
    imageType=@"mp3";
	imageId = anId;
	NSFileManager *fm = [NSFileManager defaultManager];
	if ([fm fileExistsAtPath:[self filePath]]) {
		// if we know the image extention, and we're not resuing the imageview in a cell, take advantage of iOS image caching
		if (self.delegate&&[_delegate respondsToSelector:@selector(fileSuccess:)]) {
            [_delegate fileSuccess:self.filePath];
        }
	
	} else {
		[self downloadImage];
	}
}

- (void)setImageUrl:(NSString *)url {

	if (!url) {
		self.isInResuableCell = TRUE;
		[connection cancel];
		imageId = nil;
		imageUrl = nil;
		self.filePath = nil;
		return;
	}

	imageUrl = url;
	
	NSArray *urlParts = [url componentsSeparatedByString:@"?"];
	
	if ([urlParts count] < 2) {
		[self processFullPathURL];
	} else {
		[self processQueryURL:[urlParts objectAtIndex:1]];
	}
}

- (void)processFullPathURL {
	NSArray *pathParts = [imageUrl componentsSeparatedByString:@"/"];
	NSString *filePart = [pathParts lastObject];
	NSArray *fileParts = [filePart componentsSeparatedByString:@"."];
	
	if ([fileParts count] == 2) {
		self.imageType = [fileParts objectAtIndex:1];
	}

	self.imageId = [fileParts objectAtIndex:0];
}

- (void)processQueryURL:(NSString*)query {

	// if the imageIdKey was not supplied, we can try a generic "imageId" key
	if (!imageIdKey || [imageIdKey length] == 0) {
		self.imageIdKey = defaultFileIdKey;
	}
	
	NSArray *queryParts = [query componentsSeparatedByString:@"&"];
	for (NSString *param in queryParts) {
		if ([param hasPrefix:[NSString stringWithFormat:@"%@=", imageIdKey]]) {
			NSArray *paramParts = [param componentsSeparatedByString:@"="];
			if ([paramParts count] == 2) {
				self.imageId = [paramParts objectAtIndex:1];
			}
		}
	}

	// couldn't generate an imageId, so can't cache, so download every time
	if (!imageId) {
		[self downloadImage];
	}
}

- (void)downloadImage {

	self.data = [NSMutableData data];
	NSURL *url = [NSURL URLWithString:imageUrl];
	NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
	self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)theConnection	didReceiveData:(NSData *)incrementalData {
    if (!data) self.data = [NSMutableData data];
    [data appendData:incrementalData];
}

- (void)connection:(NSURLConnection *)theConnection didFailWithError:(NSError *)error {
	NSString *url = theConnection.currentRequest.URL.absoluteString;
	NSString *msg = [NSString stringWithFormat:@"Error:\n%@\n\nWith this url:\n%@", [error description], url];
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Image Download Error" message:msg delegate:self cancelButtonTitle:@"Bummer" otherButtonTitles:nil];
	[alert show];
    if (self.delegate&&[_delegate respondsToSelector:@selector(fileFail:)]) {
        [_delegate fileFail:self.filePath];
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
	self.connection = nil;
	
	if ([theConnection.currentRequest.URL.absoluteString isEqualToString:imageUrl]) {
	    
		
		if ([imageId length] > 0) [data writeToFile:[self filePath] atomically:TRUE];
	}
    if (self.delegate&&[_delegate respondsToSelector:@selector(fileSuccess:)]) {
        NSLog(@"%@",self.filePath);
        [_delegate fileSuccess:self.filePath];
    }

	self.data = nil;
}

- (NSString*)fileName {

	 return [NSString stringWithFormat:@"%@%@%@", imageId, ([imageType length])? @"." : @"", imageType];
}

- (NSString*)filePath {

	if (!filePath) {
		NSString *imageCachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
		self.filePath = [imageCachePath stringByAppendingPathComponent:[self fileName]];
	}
	return filePath;
}

- (void)dealloc {
    [connection cancel];
}

@end
